package com.chainyoung.component_tmmarket.ui;

import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chainyoung.common.adpter.BaseFragmentAdapter;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.bean.ReqModel;
import com.chainyoung.common.common_widget.CustomViewPager;
import com.chainyoung.common.constant.CommonStringConstants;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.http.websocket.WebSoketUtils;
import com.chainyoung.common.http.websocket.WsManager;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.component_tmmarket.R;
import com.chainyoung.component_tmmarket.R2;

import com.chainyoung.component_tmmarket.bean.MarketTotal;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.gson.Gson;

import org.simple.eventbus.Subscriber;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.chainyoung.common.constant.CommonStringConstants.TRADE_NAME;
import static com.chainyoung.common.constant.CommonStringConstants.TRADE_TYPE;
import static com.chainyoung.router.RouterConstants.PATH_MARKET_KLINE;

@Route(path = PATH_MARKET_KLINE)
public class MarketKLineActivity extends BaseActivity {

    @BindView(R2.id.toolbar)
    RelativeLayout toolBar;
    @BindView(R2.id.tab_layout)
    SlidingTabLayout tabLayout;
    @BindView(R2.id.view_pager)
    CustomViewPager viewPager;
    @BindView(R2.id.tv_newest_price)
    TextView tvNewestPrice;
    @BindView(R2.id.tv_price_aud)
    TextView tvPriceAud;
    @BindView(R2.id.tv_change)
    TextView tvChange;
    @BindView(R2.id.tv_highest_price)
    TextView tvHighestPrice;
    @BindView(R2.id.tv_lowest_price)
    TextView tvLowestPrice;
    @BindView(R2.id.tv_24h_trade_amount)
    TextView tv24hAmount;

    private String currencyIn;//交易市场
    private String currencyOut;//交易区
    private List<Fragment> fragmentList = new ArrayList<>();

    private List<String> titles = new ArrayList<>();


    private WsManager wsManager;
    private String TAG = getClass().getSimpleName();

    private String topicName;
    private boolean isAlreadySubed;

    private static final int TYPE_BUY = 1;
    private static final int TYPE_SELL = 2;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {

    }

    @Override
    protected boolean setFullScreen() {
        return true;
    }

    @Override
    protected void initUI() {
        toolBar.setBackgroundColor(ContextCompat.getColor(mContext, R.color._101f32));
        mCurrentTtile.setTextColor(ContextCompat.getColor(mContext, R.color.white));
        mBarLeftImageView.setImageResource(R.mipmap.ic_back_white);

        currencyIn = getIntent().getStringExtra(CommonStringConstants.CURRENCY_IN);
        currencyOut = getIntent().getStringExtra(CommonStringConstants.CURRENCY_OUT);
        setCurrentTitle(currencyIn.toUpperCase() + "/" + currencyOut.toUpperCase());
        wsManager = WebSoketUtils.getWsManager();
        topicName = "market." + currencyIn.toLowerCase() + "_" + currencyOut.toLowerCase() + ".market";
        initView();
        initViewPager();
        viewPager.setOnCheckCanScrollListener(new CustomViewPager.OnCheckCanScrollListener() {
            @Override
            public boolean isCanScroll() {
                return false;
            }
        });

    }

    private void initView() {

    }

    private void initViewPager() {
        fragmentList.add(MarketKlineFragment.newInstance(MarketKlineFragment.TYPE_MINUTE, currencyIn, currencyOut));
        fragmentList.add(MarketKlineFragment.newInstance(MarketKlineFragment.TYPE_15_MINUTE, currencyIn, currencyOut));
        fragmentList.add(MarketKlineFragment.newInstance(MarketKlineFragment.TYPE_ONE_HOUR, currencyIn, currencyOut));
        fragmentList.add(MarketKlineFragment.newInstance(MarketKlineFragment.TYPE_FOUR_HOUR, currencyIn, currencyOut));
        fragmentList.add(MarketKlineFragment.newInstance(MarketKlineFragment.TYPE_DAY, currencyIn, currencyOut));
        titles.add("分时");
        titles.add("15分");
        titles.add("1小时");
        titles.add("4小时");
        titles.add("日线");


        viewPager.setAdapter(new BaseFragmentAdapter(getSupportFragmentManager(), fragmentList, titles));
        tabLayout.setViewPager(viewPager);
        viewPager.setOffscreenPageLimit(titles.size());
        viewPager.setCurrentItem(0, false);

    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmmarket_activity_k_line;
    }

    @OnClick(R2.id.tv_buy)
    void onBuy() {
        RouterUtils.getInstance()
                .build(RouterConstants.PATH_MAIN_MARKET_ACTIVITY)
                .withInt("page", 1)
                .withInt(TRADE_TYPE, TYPE_BUY)
                .withString(TRADE_NAME, currencyIn.toUpperCase() + "/" + currencyOut.toUpperCase())
                .navigation(mContext);
    }

    @OnClick(R2.id.tv_sell)
    void onSell() {
        RouterUtils.getInstance()
                .build(RouterConstants.PATH_MAIN_MARKET_ACTIVITY)
                .withInt("page", 1)
                .withInt(TRADE_TYPE, TYPE_SELL)
                .withString(TRADE_NAME, currencyIn.toUpperCase() + "/" + currencyOut.toUpperCase())
                .navigation(mContext);
    }


    @Override
    protected void onResume() {
        super.onResume();
        WebSoketUtils.getWsManager().startConnect();
    }

    @Override
    protected void onPause() {
        super.onPause();
        WebSoketUtils.getWsManager().stopConnect();
        WebSoketUtils.setWsManagerNull();
        isAlreadySubed = false;
    }


    private void updataView(MarketTotal.TickBean marketDetail) {
        if (marketDetail == null) {
            return;
        }
        tvNewestPrice.setText(String.format("%s", new BigDecimal(marketDetail.getLast()).setScale(6, BigDecimal.ROUND_DOWN).stripTrailingZeros().toPlainString()));
        tvPriceAud.setText(String.format("≈%s", StringUtil.subZeroAndDot(new BigDecimal(marketDetail.getCny()).setScale(2, BigDecimal.ROUND_DOWN).toPlainString() + "CNY")));
        String change=TextUtils.isEmpty(marketDetail.getChange())?"0":marketDetail.getChange();
        tvChange.setText(change + "%");
        boolean b = marketDetail.getChange().startsWith("-");

        if (TextUtils.isEmpty(marketDetail.getChange()) || Double.valueOf(marketDetail.getChange()) == 0) {
            tvChange.setTextColor(ContextCompat.getColor(mContext, R.color._7E8CA6));
            tvNewestPrice.setTextColor(ContextCompat.getColor(mContext, R.color._7E8CA6));
        } else {
            tvChange.setTextColor(!b ? ContextCompat.getColor(mContext, R.color._09C173) : ContextCompat.getColor(mContext, R.color._F95A54));
            tvNewestPrice.setTextColor(!b ? ContextCompat.getColor(mContext, R.color._09C173) : ContextCompat.getColor(mContext, R.color._F95A54));
        }
        tvHighestPrice.setText(String.format("%s", new BigDecimal(marketDetail.getHigh()).setScale(6, BigDecimal.ROUND_DOWN).stripTrailingZeros().toPlainString()));
        tvLowestPrice.setText(String.format("%s", new BigDecimal(marketDetail.getLow()).setScale(6, BigDecimal.ROUND_DOWN).stripTrailingZeros().toPlainString()));
        tv24hAmount.setText(String.format("%s", new BigDecimal(marketDetail.getVol()).stripTrailingZeros().toPlainString()));
    }

    /**
     * 次级页面获取当前最新价
     */
    public String getNewestPrice() {
        return tvNewestPrice.getText().toString().trim();
    }


    //--------------------------------------------websoket 请求---------------------------------------------------
    private void reqMarketTotalData() {
        ReqModel reqModel1 = new ReqModel();
        reqModel1.setType("req");
        reqModel1.setTopic(topicName);
        wsManager.sendMessage(new Gson().toJson(reqModel1));
    }

    private void subMarketTotalData() {
        ReqModel reqModel = new ReqModel();
        reqModel.setType("sub");
        reqModel.setTopic(topicName);
        wsManager.sendMessage(new Gson().toJson(reqModel));
    }


    //websocket 数据处理
    public void updateData(MarketTotal marketTotal) {
        updataView(marketTotal.getTick());
    }


    //---------------------------------------event-------------------------------------------

    @Subscriber
    public void onGetData(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.WS_KLINE_OPEN) {
            if (!isAlreadySubed) {
                reqMarketTotalData();
                subMarketTotalData();
                isAlreadySubed = true;
            }

        }

    }


    @Subscriber
    public void onRecieveData(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.WS_KLINE_OPEN) {
            MarketTotal marketTotal = (MarketTotal) event.getData();
            updateData(marketTotal);
        }
    }


}
